﻿(function () {
    var app = angular.module('MyControllers');
    app.controller('navigation', ['$scope', '$rootScope', '$location', '$routeParams', 'navService', function ($scope, $rootScope, $location, $routeParams, navService) {
        $scope.ls = navService;

        //绑定路由跳转成功，左导航获取和主导航的选中状态
        $scope.$on('$locationChangeSuccess', function (route, url) {
            var v = /#\/([^\/]+)/.exec(url);
            if (!v) return;
            //获取所有与当前主URL匹配的子连接
            angular.forEach(navService, function (l) {
                l.isActive = false;
                angular.forEach(l.urls, function (u) {
                    u.isActive = url.indexOf(u.link) !== -1;
                    if (u.link.indexOf(v[1]) !== -1) {
                        $scope.urls = l.urls;
                        l.isActive = true;
                    }
                });
            });
        });

        $rootScope.user = 1;

        $rootScope.$on('$stateChangeStart', function (event, toState, toParams, fromState, fromParams) {
            if (toState.name == 'login') return;// 如果是进入登录界面则允许
            // 如果用户不存在
            if (!$rootScope.user || !$rootScope.user.token) {
                event.preventDefault();// 取消默认跳转行为
                $state.go("login", { from: fromState.name, w: 'notLogin' });//跳转到登录界面
            }
        });
    }]);
})()